package com.zls.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zls.mapper.DepartmentMapper;
import com.zls.mapper.EmployeeMapper;
import com.zls.pojo.Department;
import com.zls.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {
    @Resource
    private DepartmentMapper mapper;
    @Autowired
    private EmployeeMapper empMapper;

    @Override
    @Transactional
    public int addDept(Department department) {
        int result;
        Department department1 = mapper.selectByName(department.getDeptName());
        if (department1 == null) {
            result = mapper.insertDept(department);
        } else {
            return -1;
        }
        return result;
    }

    @Override
    @Transactional
    public int editDept(Department department) {
        int result = 0;

        Department department1 = mapper.selectByName(department.getDeptName());
        if (department1 == null) {
            result = mapper.updateDept(department);
        } else {
            if (department1.getId().equals(department.getId())) {
                result = mapper.updateDept(department);
            } else {
                return -1;
            }
        }
        return result;
    }

    @Override
    @Transactional
    public int dropDeptById(Integer id) {
        int result = 0;
        int count = empMapper.selectEmpCountByDeptId(id);
        if (count == 0) {
            result = mapper.deleteById(id);
        } else {
            return -1;
        }
        return result;
    }

    @Override
    public Department getDeptById(Integer id) {
        Department department = null;
        department = mapper.selectDeptById(id);
        return department;
    }

    @Override
    public List<Department> getAll() {
        List<Department> departments = null;
        departments = mapper.selectAll();
        return departments;
    }
}
